import 'package:beamer/beamer.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:rabbit_mobile/provide/riverpod_provider.dart';
import 'package:rabbit_mobile/view/goods_details/widget/goods_details_evaluation.dart';
import 'package:rabbit_mobile/view/goods_details/widget/goods_details_footer.dart';
import 'package:rabbit_mobile/view/goods_details/widget/goods_details_info.dart';
import 'package:rabbit_mobile/view/goods_details/widget/goods_details_options.dart';
import 'package:rabbit_mobile/view/goods_details/widget/goods_details_properties.dart';
import 'package:rabbit_mobile/view/goods_details/widget/goods_details_scroll_title.dart';
import 'package:rabbit_mobile/view/goods_details/widget/goods_details_similar.dart';
import 'package:rabbit_mobile/view/goods_details/widget/goods_details_swiper.dart';
import 'package:rabbit_mobile/view/goods_details/widget/goods_details_tabbar.dart';
import 'package:rabbit_mobile/view/goods_details/widget/goods_details_title.dart';

class GoodsDetails extends ConsumerStatefulWidget {
  final String id;

  const GoodsDetails({super.key, required this.id});

  @override
  _GoodsDetailsState createState() => _GoodsDetailsState();
}

class _GoodsDetailsState extends ConsumerState<GoodsDetails> with TickerProviderStateMixin {
  /// customScroll 控制器
  late ScrollController _scrollController;

  /// tabbar 控制器
  late TabController _tabController;

  /// 透明度
  double opacityNum = 0;

  /// 接受選舉中的規格值
  String? showsSpecStr;

  /// global key
  final List<GlobalKey> _key = [
    GlobalKey(debugLabel: 'goods'),
    GlobalKey(debugLabel: 'comments'),
    GlobalKey(debugLabel: 'recomments'),
    GlobalKey(debugLabel: 'details'),
  ];

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 2, vsync: this);
    _scrollController = ScrollController();
  }

  @override
  void dispose() {
    super.dispose();
    _tabController.dispose();
    _scrollController.dispose();
  }

  // 位置計算
  double getWidgetLocation(int index) {
    RenderBox box = _key[index].currentContext?.findRenderObject() as RenderBox;
    Offset loction = box.localToGlobal(Offset.zero);
    return loction.dy;
  }

  // 滾動事件處理
  bool _handleNotificationFn(scrollNotification) {
    double goodsDy = getWidgetLocation(0);
    double commentsDy = getWidgetLocation(1);
    double recommentsDy = getWidgetLocation(2);
    double detailsDy = getWidgetLocation(3);
    if (scrollNotification.depth == 0 && scrollNotification is ScrollUpdateNotification) {
      opacityNum =
          scrollNotification.metrics.pixels / (300 - 40 + MediaQuery.of(context).padding.top);
      if (opacityNum < 0) {
        opacityNum = 0;
      } else if (opacityNum > 1) {
        opacityNum = 1;
      }
    }
    if (scrollNotification.depth == 0 && scrollNotification is ScrollEndNotification) {
      goodsDetailsScrollTitleKey.currentState!.cancelIsClick();
    }
    goodsDetailsTitleKey.currentState!.getGoodsDetailsPageOpacity(opacityNum);
    goodsDetailsScrollTitleKey.currentState!
        .getGoodsDetailsPageOpacity(opacityNum, goodsDy, commentsDy, recommentsDy, detailsDy);
    return true;
  }

  @override
  Widget build(BuildContext context) {
    final goodsDetailsData = ref.watch(goodsDetailsProvide(widget.id));
    return Scaffold(
      body: Stack(
        children: [
          Column(
            children: [
              Expanded(
                flex: 1,
                child: goodsDetailsData.when(
                  data: (data) {
                    return NotificationListener(
                      onNotification: (ScrollNotification scrollNotification) =>
                          _handleNotificationFn(scrollNotification),
                      child: CustomScrollView(
                        controller: _scrollController,
                        slivers: [
                          SliverToBoxAdapter(
                            child: Mainpicture(
                              key: _key[0],
                              list: data.mainPictures,
                            ),
                          ),
                          SliverToBoxAdapter(
                            child: GoodsDetailsInfo(
                              name: data.name,
                              desc: data.desc ?? '',
                              price: data.price,
                              mainPicture: data.mainPictures[0],
                            ),
                          ),
                          SliverToBoxAdapter(
                            child: GoodsDetailsOptions(
                              key: goodsDetailsOptionsKey,
                              imgUrl: data.mainPictures[0],
                              price: data.price,
                              oldPrice: data.oldPrice,
                              spec: data.specs,
                              skus: data.skus,
                              userAddresses: data.userAddresses,
                              showSpecsStrCallback: (String? showSpecStr) {
                                setState(() {
                                  showsSpecStr = showSpecStr;
                                });
                              },
                            ),
                          ),
                          SliverToBoxAdapter(
                            child: GoodsDetailsEvaluation(
                              key: _key[1],
                              evaluation: data.evaluationInfo,
                            ),
                          ),
                          SliverToBoxAdapter(
                            child: GoodsDetailsTabbar(key: _key[2], tabController: _tabController),
                          ),
                          SliverToBoxAdapter(
                            child: GoodsDetailsSimilar(
                              hotByDay: data.hotByDay,
                              similarProducts: data.similarProducts,
                              tabController: _tabController,
                            ),
                          ),
                          SliverToBoxAdapter(
                            child: GoodsDetailsProperties(key: _key[3], details: data.details),
                          ),
                        ],
                      ),
                    );
                  },
                  error: (error, StackTrace) {
                    return const Center(
                      child: Column(
                        children: [
                          Icon(
                            Icons.error_sharp,
                            size: 25,
                          ),
                          SizedBox(
                            height: 24,
                          ),
                          Text("數據錯誤123"),
                        ],
                      ),
                    );
                  },
                  loading: () {
                    return Image.asset('assets/loading.gif');
                  },
                ),
              ),
              const GoodsDetailsFooter(),
            ],
          ),
          GoodsDetailsTitle(key: goodsDetailsTitleKey, goodsDetailsData: goodsDetailsData),
          GoodsDetailsScrollTitle(
            key: goodsDetailsScrollTitleKey,
            titleOnTap: (index) {
              double locationY = getWidgetLocation(index);
              double point =
                  _scrollController.offset + locationY - (15 + MediaQuery.of(context).padding.top);
              _scrollController.animateTo(point,
                  duration: const Duration(milliseconds: 200), curve: Curves.linear);
            },
          ),
        ],
      ),
    );
  }
}
